package cn.com.oceansoft.nos.common.util.encrypt;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 手机用户加解密DES
 */
public class DesAPPUtils {
    private static String key="58563214";
    private static String key1 = "32128158";
    public static String decrypt(String message) throws Exception {

        byte[] bytesrc = new BASE64Decoder().decodeBuffer(message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key1.getBytes("UTF-8"));

        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte);
    }

    public static String encrypt(String message) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key1.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        return new BASE64Encoder().encode(cipher.doFinal(message.getBytes("UTF-8")));
    }



    public static void main(String[] args) throws Exception {
        String value = "123456";
        String jiami = java.net.URLEncoder.encode(value, "utf-8");

        System.out.println("加密数据:" + jiami);
        String jiamihou=encrypt(jiami);
        System.out.println("加密后数据:"+ jiamihou );
        System.out.println("解密后数据:"+decrypt("rvxSAD/OZHhlJIYhgWlXcg=="));


    }
}
